<template>
	<view :data-theme="theme" class="example container">
		<view class="header">
			<!-- 基础用法，不包含校验规则 -->
			<u--form labelPosition="left" style="margin: 0 20rpx;" :model="baseFormData" :rules="rules" ref="uForm">
				<u-form-item label="优惠券名称" borderBottom required prop="name" :labelWidth="labelWidthPx">
					<input v-model.trim="baseFormData.name" placeholder="请选择"></input>
				</u-form-item>
				<u-form-item label="优惠券类别" borderBottom :labelWidth="labelWidthPx">
					<radio-group @change="radioCategory" style="display: flex;" v-model="baseFormData.category">
						<view style="display: flex;flex-direction: row;margin: 0 20rpx;"
							v-for="(item, index) in radiolist" :key="index">
							<view>
								<radio :value="item.category" :checked="index === categoryIndex" />
							</view>
							<view style="line-height: 19px;">{{item.name}}</view>
						</view>
					</radio-group>
				</u-form-item>
				<u-form-item v-if="baseFormData.category == '2'" label="商品" borderBottom :labelWidth="labelWidthPx">
					<view style="display: flex;flex-wrap: wrap;">
						<view class="item_img" v-for="(ele,indexe) in imageList"
							style="text-align: center;position: relative;">
							<u--image :showLoading="true" :src="ele.image" width="80px" height="80px"></u--image>
							<text @click="removeImage(ele)" class="iconfont icon-guanbi5"
								style="position: absolute;right: 10rpx; top: 10rpx;font-size: 26rpx;"></text>
						</view>
						<view @click="productChoose" class="auto"
							style="text-align: center;width: 160rpx;height: 160rpx;background-color: #f4f5f7;position: relative;">
							<view class="xiangji-icon">
								<u-icon name="camera-fill" color="#d3d4d6" size="32"></u-icon>
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="优惠券面值" borderBottom required prop="money" :labelWidth="labelWidthPx">
					<uni-number-box :min="1" :max="9999" v-model="baseFormData.money" />
				</u-form-item>
				<u-form-item label="使用门槛" borderBottom prop="threshold" :labelWidth="labelWidthPx">
					<radio-group @change="radioThreshold" style="display: flex;" v-model="baseFormData.threshold">
						<view style="display: flex;flex-direction: row;margin: 0 20rpx;"
							v-for="(item, index) in thresholdList" :key="index">
							<view>
								<radio :value="item.type.toString()" :checked="index === thresholdIndex" />
							</view>
							<view style="line-height: 19px;">{{item.name}}</view>
						</view>
					</radio-group>
				</u-form-item>
				<u-form-item v-if="baseFormData.threshold" label="优惠券最低消费" borderBottom required prop="minPrice"
					:labelWidth="labelWidthPx">
					<uni-number-box :min="1" v-model="baseFormData.minPrice" />
				</u-form-item>
				<u-form-item label="使用有效期" borderBottom prop="isFixedTime" :labelWidth="labelWidthPx">
					<radio-group @change="radioIsFixedTime" style="display: flex;" v-model="baseFormData.isFixedTime">
						<view style="display: flex;flex-direction: row;margin: 0 20rpx;"
							v-for="(item, index) in isFixedTimeList" :key="index">
							<view>
								<radio :value="item.type.toString()" :checked="index === isFixedTimeIndex" />
							</view>
							<view style="line-height: 19px;">{{item.name}}</view>
						</view>
					</radio-group>
				</u-form-item>
				<u-form-item v-if="!baseFormData.isFixedTime" label="使用有效期(天)" required borderBottom
					:labelWidth="labelWidthPx">
					<uni-number-box :min="1" :max="9999" v-model="baseFormData.day" />
				</u-form-item>
				<u-form-item v-if="baseFormData.isFixedTime" label="使用有效期限" borderBottom labelWidth="100">
					<view class="example-body" style="display: flex;flex: 1;">
						<uni-datetime-picker v-model="termTime" :start="starDate" :end="end_Date" type="datetimerange"
							rangeSeparator="至" @change="changeLog" />
					</view>
				</u-form-item>
				<u-form-item label="领取是否限时" borderBottom prop="city" :labelWidth="labelWidthPx">
					<radio-group @change="radioIsTimeReceive" style="display: flex;"
						v-model="baseFormData.isTimeReceive">
						<view style="display: flex;flex-direction: row;margin: 0 20rpx;"
							v-for="(item, index) in isTimeReceiveList" :key="index">
							<view>
								<radio :value="item.type.toString()" :checked="index === isTimeReceiveIndex" />
							</view>
							<view style="line-height: 19px;">{{item.name}}</view>
						</view>
					</radio-group>
				</u-form-item>
				<u-form-item v-if="baseFormData.isTimeReceive" label="领取时间" prop="isForeverTime" borderBottom
					labelWidth="80" :required="true">
					<view class="example-body" style="display: flex;flex: 1;">
						<uni-datetime-picker v-model="isForeverTime" :start="starDate" :end="end_Date"
							type="datetimerange" rangeSeparator="至" @change="changeForeverTime" />
					</view>
				</u-form-item>
				<u-form-item label="领取方式" borderBottom prop="receiveType" labelWidth="110">
					<radio-group @change="radioReceiveType" style="display: flex;" v-model="baseFormData.receiveType">
						<view style="display: flex;flex-direction: row;margin: 0 20rpx;"
							v-for="(item, index) in receiveTypeList" :key="index">
							<view>
								<radio :value="item.type.toString()" :checked="index === receiveTypeIndex" />
							</view>
							<view style="line-height: 19px;">{{item.name}}</view>
						</view>
					</radio-group>
				</u-form-item>
				<u-form-item label="是否限量" borderBottom prop="city" :labelWidth="labelWidthPx">
					<radio-group @change="radioIsLimited" style="display: flex;" v-model="baseFormData.isLimited">
						<view style="display: flex;flex-direction: row;margin: 0 20rpx;"
							v-for="(item, index) in isLimitedList" :key="index">
							<view>
								<radio :value="item.type.toString()" :checked="index === isLimitedIndex" />
							</view>
							<view style="line-height: 19px;">{{item.name}}</view>
						</view>
					</radio-group>
				</u-form-item>
				<u-form-item v-if="baseFormData.isLimited" label="发布数量" borderBottom required prop="total"
					:labelWidth="labelWidthPx">
					<uni-number-box :min="1" :max="9999" v-model="baseFormData.total" />
				</u-form-item>
				<u-form-item label="排序" borderBottom prop="sort" :labelWidth="labelWidthPx">
					<uni-number-box :min="1" :max="9999" v-model="baseFormData.sort" />
				</u-form-item>
				<u-form-item label="状态" borderBottom prop="city" :labelWidth="labelWidthPx">
					<radio-group @change="radioStatus" style="display: flex;" v-model="baseFormData.status">
						<view style="display: flex;flex-direction: row;margin: 0 20rpx;"
							v-for="(item, index) in statusList" :key="index">
							<view>
								<radio :value="item.type.toString()" :checked="index === statusIndex" />
							</view>
							<view style="line-height: 19px;">{{item.name}}</view>
						</view>
					</radio-group>
				</u-form-item>
			</u--form>
		</view>

		<view class="footer" style="margin-top: 20rpx;">
			<view style="margin:0 20rpx 20rpx 20rpx;">
				<button class="bg_color" style="font-weight: bold;border-radius: 10px;color: #FFF;padding: 20rpx;"
					@click="saveCoupon()">立即创建</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		saveCoupondata
	} from '@/api/merchant.js';
	import {
		setThemeColor
	} from '../../../utils/setTheme';
	let app = getApp();
	export default {
		data() {
			const currentDate = this.getDate('start');
			const currentDate_end = this.getDate_end('end');
			return {
				bgColor: "#ffffff",
				theme: app.globalData.theme,

				// 基础表单数据
				baseFormData: {
					category: '1',
					isFixedTime: false,
					threshold: false,
					name: '',
					money: 1,
					minPrice: 1,
					day: null,
					isTimeReceive: true,
					productIds: '',
					receiveType: '2',
					isLimited: false,
					useStartTime: '', // 使用
					useEndTime: '', // 结束
					receiveStartTime: '', //领取
					receiveEndTime: '',
					sort: 0,
					total: 1,
					status: true,
					checked: [],
				},
				isForeverTime: [], //领取时间
				labelWidthPx: '240rpx',
				termTime: [], //使用有效期限
				radiolist: [{
					name: '商家券',
					category: '1',
				}, {
					name: '商品券',
					category: '2',
				}],
				categoryIndex: 0,
				thresholdList: [{
					name: '无门槛',
					type: false,
				}, {
					name: '有门槛',
					type: true,
				}],
				thresholdIndex: 0,
				isFixedTimeList: [{
					name: '天数',
					type: false,
				}, {
					name: '时间段',
					type: true,
				}],
				isFixedTimeIndex: 0,
				isTimeReceiveList: [{
					name: '限时',
					type: true,
				}, {
					name: '不限时',
					type: false,
				}],
				isTimeReceiveIndex: 0,
				receiveTypeList: [{
					name: '手动领取',
					type: '1',
				}, {
					name: '商品买赠券',
					type: '2',
				}],
				receiveTypeIndex: 1,
				isLimitedList: [{
					name: '不限量',
					type: false,
				}, {
					name: '限量',
					type: true,
				}],
				isLimitedIndex: 0,
				statusList: [{
					name: '开启',
					type: true,
				}, {
					name: '关闭',
					type: false,
				}],
				statusIndex: 0,
				// 校验
				rules: {
					name: [{
						required: true,
						message: '请输入优惠券名称',
						trigger: ['blur', 'change']
					}],
				},
				fileList1: [
					// {
					// 	url:"https://p3.ssl.qhimg.com/t0137f6f23e234057d6.webp",
					// }
				], //商品封面图
				starDate: currentDate,
				end_Date: currentDate_end,
				imageList: [], //商品券展示图片
			};
		},
		computed: {
			currentDate() {
				return this.getDate('start');
			},
			currentDate_end() {
				return this.getDate_end('end');
			}
		},
		onLoad() {
			this.bgColor = setThemeColor();
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			
		},
		methods: {
			// 优惠券类别
			radioCategory(ele) {
				let category = JSON.parse(ele.detail.value)
				this.$set(this.baseFormData, 'category', category)
			},
			/** 
			 * 商品券
			 */
			otherFun(seleProductArray) {
				this.imageList.push(...seleProductArray);
			},
			removeImage(i) {
				this.imageList.splice(i, 1);
			},
			// 使用门槛
			radioThreshold(ele) {
				let thresholdValue = JSON.parse(ele.detail.value)
				this.$set(this.baseFormData, 'threshold', thresholdValue)
			},
			//使用有效期(天)
			radioIsFixedTime(ele) {
				let isFixedValue = JSON.parse(ele.detail.value)
				this.$set(this.baseFormData, 'isFixedTime', isFixedValue)
			},
			// 使用有效期限
			changeLog(time) {
				this.termTime = time;
			},
			// 领取是否限时
			radioIsTimeReceive(ele) {
				let timeReceive = JSON.parse(ele.detail.value)
				this.$set(this.baseFormData, 'isTimeReceive', timeReceive);
			},
			// 领取时间
			changeForeverTime(time) {
				this.isForeverTime = time;
			},
			//是否限量
			radioIsLimited(ele) {
				this.$set(this.baseFormData, 'isLimited', JSON.parse(ele.detail.value))
			},

			radioReceiveType(ele) {
				this.$set(this.baseFormData, 'receiveType', JSON.parse(ele.detail.value))
			},
			productChoose() {
				this.goPage(`/pages/marketing/productChoose/productChoose?data=` + JSON.stringify(this.imageList));
			},
			goPage(url) {
				uni.navigateTo({
					url
				})
			},

			// -----------------
			//创建数据
			saveCoupon() {
				let that = this;
				if (this.imageList.length > 0) {
					that.baseFormData.productIds = that.imageList.map((item) => {
						return item.id;
					}).join(',');
				};
				this.$refs.uForm.validate().then(res => {
					if ((this.baseFormData.isFixedTime && !this.termTime) || (this.baseFormData.isFixedTime && !
							this.termTime
							.length))
						return uni.$u.toast('请选择使用有效期限');
					if (!this.baseFormData.isFixedTime && this.baseFormData.day == null)
						return uni.$u.toast('请输入天数');
					if (
						(this.baseFormData.isTimeReceive && !this.isForeverTime) ||
						(this.baseFormData.isTimeReceive && !this.isForeverTime.length)
					)
						return uni.$u.toast('请选择请选择领取时间');
					if (!this.baseFormData.threshold) this.baseFormData.minPrice = 0;
					if (!this.baseFormData.isLimited) this.baseFormData.total = 0;
					this.baseFormData.isFixedTime && this.termTime.length ?
						((this.baseFormData.useStartTime = this.termTime[0]), (this.baseFormData.day = null)) :
						(this.baseFormData.useStartTime = '');
					this.baseFormData.isFixedTime && this.termTime.length ?
						((this.baseFormData.useEndTime = this.termTime[1]), (this.baseFormData.day = null)) :
						(this.baseFormData.useEndTime = '');
					this.baseFormData.isTimeReceive && this.isForeverTime.length ?
						(this.baseFormData.receiveStartTime = this.isForeverTime[0]) :
						(this.baseFormData.receiveStartTime = '');
					this.baseFormData.isTimeReceive && this.isForeverTime.length ?
						(this.baseFormData.receiveEndTime = this.isForeverTime[1]) :
						(this.baseFormData.receiveEndTime = '');
					let saveData = this.baseFormData;
					saveCoupondata(saveData).then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: '创建成功',
								icon: 'success', // 提示图标，可选值：'success', 'loading', 'none'
								duration: 2000 // 持续时间，单位为毫秒
							});
							const pages =
								getCurrentPages(); // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
							const prevPage = pages[pages.length - 2]; // 获取上一级页面对象
							uni.navigateBack({
								delta: 1,
							});
						}
					})
				})
			},
			//-----------------------------------------------------------优惠券开始日期
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let month_end = date.getMonth() + 2;
				let day = date.getDate();
				let hours = date.getHours();
				let minutes = date.getMinutes();
				let seconds = date.getSeconds();

				if (type == 'start') {
					year = year;
				} else if (type == 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				hours = hours > 9 ? hours : '0' + hours;
				minutes = minutes > 9 ? minutes : '0' + minutes;
				seconds = seconds > 9 ? seconds : '0' + seconds;
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			//-----------------------------------------------------优惠券结束时间
			getDate_end(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 2;
				let day = date.getDate();

				if (type == 'start') {
					year = year - 60;
				} else if (type == 'end') {
					year = year + 20;
				}

				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
		}
	}
</script>

<style lang="scss">
	.bg_color {
		@include main_bg_color(theme);
	}

	.plain_bgColor {
		@include main_color(theme);
		@include main_bg_rgba_color(theme, 0.05);
		border: 1rpx solid;
	}

	page {
		height: 100%;
	}

	.container {
		display: flex;
		flex-direction: column;
		// height: 100%;
	}

	// .header {
	// 	background-color: #fff;
	// }

	.auto {
		margin: 10rpx;
	}

	.auto .xiangji-icon {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.item_img {
		margin: 10rpx;
	}

	.example {
		background-color: #fff;
		margin: 20rpx;
		border-radius: 20rpx;
		padding: 20rpx;
	}
</style>